package com.aiyige.utils;

import android.text.TextUtils;

import com.tencent.smtt.sdk.WebView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class WebViewUtil {
    public static void callJs(WebView webView, String js) {
        webView.loadUrl("javascript:" + js);
    }


    public static void callJsMethod(WebView webView, String method, String... params) {
        StringBuilder builder = new StringBuilder();
        builder.append("javascript:" + method);
        if (params == null || params.length == 0) {
            builder.append("()");
        } else {
            builder.append("(").append(concat(params)).append(")");
        }
        webView.loadUrl(builder.toString());
    }

    private static String concat(String... params) {

        StringBuilder mStringBuilder = new StringBuilder();

        for (int i = 0; i < params.length; i++) {
            String param = params[i];
            if (!isJson(param)) {
                mStringBuilder.append("\"").append(param).append("\"");
            } else {
                mStringBuilder.append(param);
            }
            if (i != params.length - 1) {
                mStringBuilder.append(" , ");
            }
        }

        return mStringBuilder.toString();
    }

    private static boolean isJson(String target) {
        if (TextUtils.isEmpty(target))
            return false;

        boolean tag = false;
        try {
            if (target.startsWith("["))
                new JSONArray(target);
            else
                new JSONObject(target);

            tag = true;
        } catch (JSONException igonre) {
//            igonre.printStackTrace();
            tag = false;
        }

        return tag;
    }


}
